<template>
  <div class="gen-head-img">
    <div class="api-config">
      <div class="section-title">API配置</div>
      <el-form label-position="top">
        <el-form-item label="工作流Token">
          <el-input v-model="workflowToken" placeholder="请输入Coze工作流Token" />
        </el-form-item>
        <el-form-item label="工作流ID">
          <el-input v-model="workflowId" placeholder="请输入Coze工作流ID" />
        </el-form-item>
      </el-form>
    </div>
    
    <div class="image-upload">
      <div class="section-title">上传图片</div>
      <el-upload
        class="upload-container"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleImageChange"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽图片到此处或 <em>点击上传</em>
        </div>
      </el-upload>
      <div v-if="selectedImage" class="preview-container">
        <img :src="selectedImage" class="preview-image" />
        <el-button @click="clearImage" type="danger" size="small">清除图片</el-button>
      </div>
    </div>

    <div class="prompt-container">
      <div class="section-title">提示词</div>
      <el-input
        v-model="customPrompt"
        type="textarea"
        :rows="3"
        placeholder="输入自定义提示词"
      />
    </div>

    <div class="style-selection">
      <div class="section-title">风格选择</div>
      <el-checkbox-group v-model="selectedStyles">
        <el-checkbox v-for="style in presetStyles" :key="style.id" :label="style.id">
          {{ style.name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>

    <div class="selected-styles-preview" v-if="selectedStyles.length > 0 || customPrompt">
      <div class="section-title">合成提示词预览：</div>
      <div class="prompt-preview">{{ finalPrompt }}</div>
    </div>

    <div class="generate-container">
      <el-button type="primary" @click="generateImage" :loading="isGenerating" :disabled="!canGenerate" style="width: 100%;">
        生成图片
      </el-button>
    </div>

    <div v-if="generatedImage" class="result-container">
      <div class="section-title">生成结果：</div>
      <img :src="generatedImage" class="result-image" />
      <el-button @click="downloadImage" type="success" style="margin-top: 10px;">下载图片</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { CozeAPI } from '@coze/api'

// 工作流相关
const workflowToken = ref('')
const workflowId = ref('')
const customPrompt = ref('')
const selectedImage = ref(null)
const rawFile = ref(null)
const isGenerating = ref(false)
const generatedImage = ref(null)

// 风格预设
const presetStyles = [
  { id: 1, name: '水彩风格', prompt: 'watercolor style, soft colors, artistic' },
  { id: 2, name: '油画风格', prompt: 'oil painting style, textured, rich colors' },
  { id: 3, name: '像素艺术', prompt: 'pixel art, 8-bit style, retro gaming' },
  { id: 4, name: '赛博朋克', prompt: 'cyberpunk, neon lights, futuristic, high tech' },
  { id: 5, name: '动漫风格', prompt: 'anime style, cel shaded, vibrant colors' },
  { id: 6, name: '黑白素描', prompt: 'black and white sketch, pencil drawing' },
  { id: 7, name: '梦幻风格', prompt: 'dreamy, ethereal, soft focus, pastel colors' },
  { id: 8, name: '复古风格', prompt: 'vintage, retro, old photograph, sepia tones' }
]

const selectedStyles = ref([])

// 计算最终提示词
const finalPrompt = computed(() => {
  const stylePrompts = selectedStyles.value
    .map(styleId => presetStyles.find(style => style.id === styleId)?.prompt || '')
    .filter(prompt => prompt !== '')
    .join(', ')
  
  return [customPrompt.value, stylePrompts].filter(p => p).join(', ')
})

// 是否可以生成图片
const canGenerate = computed(() => {
  return workflowToken.value.trim() !== '' && 
         workflowId.value.trim() !== '' &&
         (selectedImage.value !== null || finalPrompt.value.trim() !== '')
})

// 处理图片选择
const handleImageChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件!')
    return
  }
  
  rawFile.value = file.raw
  const reader = new FileReader()
  reader.onload = (e) => {
    selectedImage.value = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 清除选择的图片
const clearImage = () => {
  selectedImage.value = null
  rawFile.value = null
}

// 生成图片
const generateImage = async () => {
  if (!canGenerate.value) {
    ElMessage.warning('请填写工作流Token、工作流ID和提示词或上传图片!')
    return
  }

  try {
    isGenerating.value = true
    
    // 创建Coze客户端，使用正确的CozeAPI类
    const cozeClient = new CozeAPI({
      token: workflowToken.value,
      allowPersonalAccessTokenInBrowser: true
    })
    
    // 准备工作流参数
    const params = {}
    
    // 设置提示词参数
    if (finalPrompt.value) {
      params.prompt = finalPrompt.value
    }
    
    // 如果有图片，上传图片
    if (rawFile.value) {
      try {
        // 使用Coze API上传文件
        const uploadResponse = await cozeClient.files.upload({
          file: rawFile.value
        })
        
        if (uploadResponse && uploadResponse.data) {
          // 添加文件信息到参数中
          params.img = uploadResponse.data
        } else {
          throw new Error('文件上传返回数据格式不正确')
        }
      } catch (uploadError) {
        console.error('上传文件失败:', uploadError)
        throw new Error(`上传图片失败: ${uploadError.message || '未知错误'}`)
      }
    }
    
    try {
      // 调用工作流
      const workflowResponse = await cozeClient.workflows.run({
        workflow_id: workflowId.value,
        params: params
      })
      
      // 处理结果
      if (workflowResponse && workflowResponse.data) {
        let imageUrl = null
        
        // 按优先级尝试不同的位置获取图片URL
        if (typeof workflowResponse.data.response === 'string' && 
            workflowResponse.data.response.startsWith('http')) {
          // 如果响应直接是URL字符串
          imageUrl = workflowResponse.data.response
        } else if (workflowResponse.data.response && workflowResponse.data.response.image_url) {
          // 如果图片URL在response.image_url中
          imageUrl = workflowResponse.data.response.image_url
        } else if (workflowResponse.data.response && workflowResponse.data.response.url) {
          // 如果图片URL在response.url中
          imageUrl = workflowResponse.data.response.url
        } else if (workflowResponse.data.image_url) {
          // 如果图片URL在顶层的image_url中
          imageUrl = workflowResponse.data.image_url
        } else if (workflowResponse.data.url) {
          // 如果图片URL在顶层的url中
          imageUrl = workflowResponse.data.url
        }
        
        if (imageUrl) {
          generatedImage.value = imageUrl
          ElMessage.success('图片生成成功!')
        } else {
          // 如果找不到图片URL，显示响应内容用于调试
          console.warn('无法找到图片URL，工作流返回:', workflowResponse.data)
          throw new Error('工作流未返回有效的图片URL')
        }
      } else {
        throw new Error('工作流未返回有效数据')
      }
    } catch (workflowError) {
      console.error('调用工作流失败:', workflowError)
      throw new Error(`调用工作流失败: ${workflowError.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('生成图片出错:', error)
    ElMessage.error(`生成失败: ${error.message}`)
  } finally {
    isGenerating.value = false
  }
}

// 下载生成的图片
const downloadImage = () => {
  if (!generatedImage.value) return
  
  const link = document.createElement('a')
  link.href = generatedImage.value
  link.download = `ai-generated-image-${new Date().getTime()}.png`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<style scoped>
.gen-head-img {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.api-config,
.image-upload,
.prompt-container,
.style-selection,
.generate-container,
.result-container,
.selected-styles-preview {
  margin-bottom: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #f8f9fa;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 16px;
  color: #303133;
}

.preview-container {
  margin-top: 15px;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.result-image {
  max-width: 100%;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.prompt-preview {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  font-size: 14px;
  color: #5a5e66;
  word-break: break-word;
  border: 1px dashed #dcdfe6;
}

.upload-container {
  width: 100%;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-checkbox {
  margin-right: 0 !important;
}
</style>